package com.lanou3g.code0522.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

//统计在线人数
//listener就是全局唯一的
@WebListener
public class CountListener implements HttpSessionListener {
    private int count = 0;

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        HttpSession session = httpSessionEvent.getSession();
        ServletContext app = session.getServletContext();
        Integer count= (Integer) app.getAttribute("count");
        if (count==null){
            count=0;
        }
        count++;
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
       HttpSession session = httpSessionEvent.getSession();
       ServletContext app = session.getServletContext();
       Integer count = (Integer) app.getAttribute("count");
       count--;
       app.setAttribute("count",count);
    }
}
